package com.chenzouquan.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.databind.JsonNode;

/**
 * JSON转util工具类
 */
public class JsonToXmlConverter {
    String jsonFilePath = "path/to/json/file.json"; // JSON文件路径

    String xmlFilePath = "path/to/xml/file.xml"; // 要保存的XML文件路径

    /**
     * JSON转xml工具函数
     * @param jsonFilePath JSON文件路径
     * @param xmlFilePath 要保存的XML文件路径
     * @return
     */
    public boolean change(String jsonFilePath, String xmlFilePath) {
        try {
            // 创建ObjectMapper和XmlMapper对象
            ObjectMapper objectMapper = new ObjectMapper();
            XmlMapper xmlMapper = new XmlMapper();

            // 读取JSON文件并解析为JsonNode对象
            JsonNode jsonNode = objectMapper.readTree(new File(jsonFilePath));
            if (jsonNode.isArray()){
                ObjectNode jsonObject1 = objectMapper.createObjectNode();
                jsonObject1.set("data",jsonNode);
                jsonNode = jsonObject1;
            }
            // 将JsonNode对象转换为XML字符串
            String xmlString = xmlMapper.writer().withRootName("root").writeValueAsString(jsonNode);

            // 将XML字符串写入XML文件
            xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
            xmlMapper.writeValue(new File(xmlFilePath), jsonNode);

            System.out.println("JSON转换为XML成功");
            // 删除原文件
            new File(jsonFilePath).delete();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 删除原文件
        new File(jsonFilePath).delete();
        return false;
    }
}
